const mime = require("mime");
const path = require("path");
/**
 * 这个中间件负责提供产出的预览
 * 拦截 http 请求，看看请求的文件是不是 webpack 打包出来的文件
 * 如果是的话 从磁盘读出来 返回给客户端
 */
function wrapper({ fs, outputPath }) {
  return (req, res, next) => {
    let url = req.url;
    console.log("url", url);

    if (req.url === "/favicon.ico") return res.sendStatus(404);

    if (url === "/") url = "/index.html";

    const filename = path.join(outputPath, url);
    console.log(filename);

    try {
      const stat = fs.statSync(filename);
      if (stat.isFile()) {
        const content = fs.readFileSync(filename);
        console.log("content", content);

        res.setHeader("Content-Type", mime.getType(filename));
        return res.send(content);
      } else {
        return res.sendStatus(404);
      }
    } catch (error) {
      console.error(error);
      return next(error);
    }
  };
}

module.exports = wrapper;
